import React, { useEffect } from 'react';
import { connect } from 'react-redux'
import Banner from '../../../components/Banner'
import logo from '../../../logo192.png'
import { getList } from '../../../api'
import ListItem from '../../../components/ListItem'

const bannerList = [logo, logo, logo, logo, logo]

const Index = ({ list, setList }) => {
  const getListAndSet = async () => {
    console.log('请求数据 getList');
    const resp = await getList()
    console.log('分发 dispatch');
    setList(resp.data.data)
  }

  useEffect(() => {
    console.log('页面完毕');
    getListAndSet()
  }, [])

  return (
    <div className="main">
      <Banner banners={bannerList}></Banner>
      {
        list.length > 0 && list.map((v, i) => {
          return <ListItem key={i} {...v}></ListItem>
        })
      }
    </div>
  );
}

const mapStateToProps = state => {
  return state
}

const mapDiapatchToProps = dispatch => {
  return {
    setList(payload) {
      console.log('dispath: setList', '提交action SET_LIST');
      dispatch({ type: 'SET_LIST', payload })
    }
  }
}

export default connect(mapStateToProps, mapDiapatchToProps)(Index);

// 1、 创建仓库
// const reducer = (state, action) => {
//   // 必须有返回值
// }
// const store = createStore(reduce)
// export default store
// 2. 在react 组件中使用 store 的数据
//  2-1  建立链接
/**
 * import { Provider }  from 'react-redux'
 *
 * <Provider>  <组件 /> </Provider>
 * */
// 2-2 被包裹的组件 如果使用数据
/**
 * import { connect } from 'react-redux'
 * const mapStateToProps = ({ list }) => {
 *   return {
 *      list,
 *    }
 * }
 *
 * export default connect(mapStateToProps)(组件)
 * 该组件 就可以使用props.list 来自于 store 的数据
*/